document.addEventListener('DOMContentLoaded', function() {
    // 更新当前时间
    function updateCurrentTime() {
        const now = new Date();
        const options = {
            year: 'numeric',
            month: 'long',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        };
        const timeElement = document.getElementById('current-time');
        if (timeElement) {
            timeElement.textContent = now.toLocaleDateString('zh-CN', options);
        }
    }
    
    updateCurrentTime();
    setInterval(updateCurrentTime, 1000);
    
    // 移动端侧边栏控制
    const mobileSidebar = document.getElementById('mobile-sidebar');
    const sidebarOverlay = document.getElementById('sidebar-overlay');
    const menuButton = document.getElementById('menu-button');
    
    if (mobileSidebar && sidebarOverlay) {
        function closeSidebarMenu() {
            mobileSidebar.classList.add('-translate-x-full');
            sidebarOverlay.classList.add('opacity-0', 'pointer-events-none');
            document.body.classList.remove('overflow-hidden');
        }
        
        function openSidebarMenu() {
            mobileSidebar.classList.remove('-translate-x-full');
            sidebarOverlay.classList.remove('opacity-0', 'pointer-events-none');
            document.body.classList.add('overflow-hidden');
        }
        
        document.getElementById('close-sidebar').addEventListener('click', closeSidebarMenu);
        sidebarOverlay.addEventListener('click', closeSidebarMenu);
        
        if (menuButton) {
            menuButton.addEventListener('click', openSidebarMenu);
        }
        
        // ESC键关闭侧边栏
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && !mobileSidebar.classList.contains('-translate-x-full')) {
                closeSidebarMenu();
            }
        });
    }
    
    // 桌面端侧边栏控制
    const toggleDesktopSidebar = document.getElementById('toggle-desktop-sidebar');
    const desktopSidebar = document.getElementById('desktop-sidebar');
    const sidebarIcon = document.getElementById('sidebar-icon');
    
    if (toggleDesktopSidebar && desktopSidebar && sidebarIcon) {
        function toggleSidebar() {
            // 检查侧边栏当前是否折叠
            const isCollapsed = desktopSidebar.classList.contains('w-20');
            
            if (isCollapsed) {
                // 展开侧边栏
                desktopSidebar.classList.remove('w-20');
                desktopSidebar.classList.add('w-64');
                sidebarIcon.classList.remove('fa-chevron-right');
                sidebarIcon.classList.add('fa-chevron-left');
                
                // 显示菜单项文本（添加淡入动画）
                setTimeout(() => {
                    document.querySelectorAll('.nav-item span').forEach(span => {
                        span.classList.remove('hidden');
                        span.classList.add('opacity-0');
                        setTimeout(() => {
                            span.classList.remove('opacity-0');
                        }, 50);
                    });
                    const menuLabel = document.querySelector('.text-xs.font-semibold.text-gray-500');
                    if (menuLabel) {
                        menuLabel.classList.remove('hidden');
                        menuLabel.classList.add('opacity-0');
                        setTimeout(() => {
                            menuLabel.classList.remove('opacity-0');
                        }, 50);
                    }
                }, 100);
                
                // 保存侧边栏状态
                localStorage.setItem('sidebarCollapsed', 'false');
            } else {
                // 折叠侧边栏
                // 先隐藏菜单项文本
                document.querySelectorAll('.nav-item span').forEach(span => {
                    span.classList.add('opacity-0');
                });
                const menuLabel = document.querySelector('.text-xs.font-semibold.text-gray-500');
                if (menuLabel) {
                    menuLabel.classList.add('opacity-0');
                }
                
                // 延迟改变宽度，等待文本消失
                setTimeout(() => {
                    desktopSidebar.classList.remove('w-64');
                    desktopSidebar.classList.add('w-20');
                    sidebarIcon.classList.remove('fa-chevron-left');
                    sidebarIcon.classList.add('fa-chevron-right');
                    
                    // 完全隐藏文本
                    document.querySelectorAll('.nav-item span').forEach(span => {
                        span.classList.add('hidden');
                        span.classList.remove('opacity-0');
                    });
                    if (menuLabel) {
                        menuLabel.classList.add('hidden');
                        menuLabel.classList.remove('opacity-0');
                    }
                }, 200);
                
                // 保存侧边栏状态
                localStorage.setItem('sidebarCollapsed', 'true');
            }
        }
        
        toggleDesktopSidebar.addEventListener('click', toggleSidebar);
        
        // 从localStorage恢复侧边栏状态
        const isSidebarCollapsed = localStorage.getItem('sidebarCollapsed') === 'true';
        if (isSidebarCollapsed) {
            // 如果之前是折叠状态，应用折叠样式
            desktopSidebar.classList.remove('w-64');
            desktopSidebar.classList.add('w-20');
            sidebarIcon.classList.remove('fa-chevron-left');
            sidebarIcon.classList.add('fa-chevron-right');
            
            // 隐藏菜单项文本
            document.querySelectorAll('.nav-item span').forEach(span => {
                span.classList.add('hidden');
            });
            const menuLabel = document.querySelector('.text-xs.font-semibold.text-gray-500');
            if (menuLabel) {
                menuLabel.classList.add('hidden');
            }
        }
    }
    
    // 通用工具函数
    window.showNotification = function(message, type = 'info') {
        // 检查是否已存在通知元素
        let notification = document.getElementById('notification');
        if (!notification) {
            notification = document.createElement('div');
            notification.id = 'notification';
            notification.className = 'notification';
            document.body.appendChild(notification);
        }
        
        // 设置通知类型样式
        notification.className = 'notification';
        
        if (type === 'success') {
            notification.classList.add('success');
            notification.innerHTML = `<i class="fa fa-check-circle mr-2"></i>${message}`;
        } else if (type === 'error') {
            notification.classList.add('error');
            notification.innerHTML = `<i class="fa fa-exclamation-circle mr-2"></i>${message}`;
        } else {
            notification.classList.add('info');
            notification.innerHTML = `<i class="fa fa-info-circle mr-2"></i>${message}`;
        }
        
        // 显示通知
        setTimeout(() => {
            notification.classList.add('show');
        }, 10);
        
        // 3秒后隐藏通知
        setTimeout(() => {
            notification.classList.remove('show');
        }, 3000);
    };
    
    // 防抖函数
    window.debounce = function(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    };
    
    // 节流函数
    window.throttle = function(func, limit) {
        let inThrottle;
        return function() {
            const args = arguments;
            const context = this;
            if (!inThrottle) {
                func.apply(context, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    };
    
    // 帮助文档弹窗功能 (修改部分)
    const helpButton = document.getElementById('help-button');
    const helpModal = document.getElementById('help-modal');
    const helpModalOverlay = document.getElementById('help-modal-overlay');
    const closeHelpModal = document.getElementById('close-help-modal');
    const helpModalCloseBtn = document.getElementById('help-modal-close-btn');
    const modalContent = helpModal ? helpModal.querySelector('div[class*="bg-white"]') : null;
    
    // 确保所有元素都存在
    if (helpButton && helpModal && helpModalOverlay && closeHelpModal && helpModalCloseBtn && modalContent) {
        // 显示帮助弹窗
        function showHelpModal() {
            helpModal.classList.remove('hidden');
            document.body.classList.add('overflow-hidden');
            
            // 触发重排后添加动画类
            setTimeout(() => {
                helpModal.classList.add('opacity-100');
                helpModalOverlay.classList.add('opacity-100');
                modalContent.classList.remove('scale-95');
                modalContent.classList.add('scale-100');
            }, 10);
        }
        
        // 隐藏帮助弹窗
        function hideHelpModal() {
            helpModal.classList.remove('opacity-100');
            helpModalOverlay.classList.remove('opacity-100');
            modalContent.classList.remove('scale-100');
            modalContent.classList.add('scale-95');
            
            setTimeout(() => {
                helpModal.classList.add('hidden');
                document.body.classList.remove('overflow-hidden');
            }, 300);
        }
        
        // 绑定所有点击事件
        helpButton.addEventListener('click', showHelpModal);
        closeHelpModal.addEventListener('click', hideHelpModal);
        helpModalCloseBtn.addEventListener('click', hideHelpModal);
        helpModalOverlay.addEventListener('click', hideHelpModal);
        
        // ESC键关闭弹窗
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && !helpModal.classList.contains('hidden')) {
                hideHelpModal();
            }
        });
    } else {
            console.error('帮助弹窗元素缺失，无法初始化帮助功能');
        }
        
        // 用户中心下拉菜单交互逻辑
        const userDropdownButton = document.getElementById('user-dropdown-button');
        const userDropdownContent = document.getElementById('user-dropdown-content');
        
        if (userDropdownButton && userDropdownContent) {
            // 显示/隐藏下拉菜单
            function toggleUserDropdown() {
                const dropdown = userDropdownButton.closest('.user-dropdown');
                dropdown.classList.toggle('open');
                
                // 旋转下拉箭头
                const arrowIcon = userDropdownButton.querySelector('.fa-chevron-down');
                if (arrowIcon) {
                    arrowIcon.style.transform = dropdown.classList.contains('open') ? 'rotate(180deg)' : 'rotate(0)';
                }
            }
            
            // 隐藏所有下拉菜单
            function hideAllDropdowns() {
                document.querySelectorAll('.user-dropdown').forEach(dropdown => {
                    dropdown.classList.remove('open');
                    const arrowIcon = dropdown.querySelector('.fa-chevron-down');
                    if (arrowIcon) {
                        arrowIcon.style.transform = 'rotate(0)';
                    }
                });
            }
            
            // 点击用户按钮时切换下拉菜单
            userDropdownButton.addEventListener('click', function(e) {
                e.stopPropagation(); // 阻止事件冒泡
                toggleUserDropdown();
            });
            
            // 点击下拉菜单内容时阻止事件冒泡
            userDropdownContent.addEventListener('click', function(e) {
                e.stopPropagation();
            });
            
            // 点击其他区域时隐藏下拉菜单
            document.addEventListener('click', function() {
                hideAllDropdowns();
            });
            
            // ESC键关闭下拉菜单
            document.addEventListener('keydown', function(e) {
                if (e.key === 'Escape') {
                    hideAllDropdowns();
                }
            });
        }
});